<?php

namespace common\models;

use Yii;

class BaseModel extends \yii\db\ActiveRecord
{

    public function _save($data = array(), $allErrors = 1)
    {
        if ($this->load($data, '') && $this->save()) {
            return true;
        }
        if ($allErrors) {
            return $this->getErrors();
        } else {
            $errors = $this->getFirstErrors();
            return reset($errors);
        }
    }

	protected function autosaveTimestamp($withUpdate = 1)
    {
    	if ($withUpdate == 1) {
    		$attributes = [
    			\yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
    		];
    	} else {
    		$attributes = [
    			\yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
    		];
    	}
    	return [
            'class' => \yii\behaviors\TimestampBehavior::className(),
            'attributes' => $attributes,
        ];
    }

    protected function autosaveUid()
    {
        return [
            'class' => \yii\behaviors\AttributeBehavior::className(),
            'attributes' => [
                \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => 'updated_uid',
                \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_uid',
            ],
            'value' => function ($event) {
                return Yii::$app->user->id;
            },
        ];
    }

    public static function insertAll($data)
    {
        if (empty($data) || !is_array($data)) {
            return 0;
        }
        $columns = [];
        $rows = [];
        foreach ($data as $k => $v) {
            foreach ($v as $key => $val) {
                if ($k == 0) {
                    $columns[] = $key;
                }
                $rows[$k][] = $val;
            }
        }
        return Yii::$app->db->createCommand()->batchInsert(self::tableName(), $columns, $rows)->execute();
    }
}